package com.xjh.t.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjh.t.common.DataGridView;
import com.xjh.t.common.ResultObj;
import com.xjh.t.common.WebUtils;
import com.xjh.t.domain.*;
import com.xjh.t.service.*;
import com.xjh.t.vo.OrderGoodsVo;
import com.xjh.t.vo.OrderVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author satela
 * @since 2025-11-15
 */
@RestController
@RequestMapping("/order-goods")
public class OrderGoodsController {

    @Autowired
    private IOrderGoodsService orderGoodsService;

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private ISalerService salerService;

    @Autowired
    private IGoodsService goodsService;

    @RequestMapping("getOrderGoodsList")
    public DataGridView getOrderGoodsList(OrderGoodsVo order) {

         HttpSession session = WebUtils.getSession();
         User user =(User) session.getAttribute("user");

        IPage<OrderGoods> page = new Page<>(order.getPage(), order.getLimit());

        QueryWrapper<OrderGoods> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq(order.getState()!= null && order.getState() < 4,"state",order.getState());
        List<Integer> currentUserRoleIds=this.roleService.queryUserRoleIdsByUid(user.getId());
        boolean isSaler = currentUserRoleIds.indexOf(4) >= 0;
        if(isSaler)
        {
            QueryWrapper<Saler> salerQueryWrapper = new QueryWrapper<>();
            salerQueryWrapper.eq("mobile_phone",user.getName());
            List<Saler> salerList = salerService.list(salerQueryWrapper);
            if(salerList.size() > 0)
            {
                orderQueryWrapper.eq("belong_saler",salerList.get(0).getId());
            }
        }
        if(StringUtils.isNotBlank(order.getUserPhone())) {

            QueryWrapper<ClientUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.like(order.getUserPhone() != null, "user_phone", order.getUserPhone());
            List<ClientUser> clientUsers = clientUserService.list(userQueryWrapper);

            if(clientUsers.size() > 0)
            {
                List<Integer> userids = new ArrayList<>();
                for(ClientUser clientUser:clientUsers)
                    userids.add(clientUser.getId());
                orderQueryWrapper.in("user_id",userids);
            }

        }

        orderQueryWrapper.eq("has_pay",1);

        orderQueryWrapper.ge(order.getStartTime() != null, "confirm_time", order.getStartTime());
        orderQueryWrapper.le(order.getEndTime() != null, "confirm_time", order.getEndTime());


        orderQueryWrapper.orderByDesc("confirm_time");

        this.orderGoodsService.page(page, orderQueryWrapper);
        List<OrderGoods> orderList = page.getRecords();

        List<OrderGoodsVo> orderVoList = new ArrayList<>();
        for(OrderGoods order1:orderList)
        {
            OrderGoodsVo orderVo = new OrderGoodsVo();
            BeanUtils.copyProperties(order1,orderVo);


            Saler saler = salerService.getById(order1.getBelongSaler());
            if(saler != null)
                orderVo.setSalerName(saler.getSalerName());
            Goods goods = goodsService.getById(order1.getGoodsId());
            orderVo.setGoodsImg(goods.getGoodsImg());
            //orderVoList.add(orderVo);

            ClientUser clientUser = clientUserService.getById(order1.getUserId());
            if(clientUser != null) {

                orderVo.setUserPhone(clientUser.getUrPhone());
                orderVoList.add(orderVo);
            }
        }

        List<OrderGoods> orderInfos = this.orderGoodsService.list(orderQueryWrapper);
        //sqlsession.close();

        BigDecimal amount = new BigDecimal(0);

        for(OrderGoods orderInfo:orderInfos)
        {
            try {
                amount = amount.add(orderInfo.getSalerPrice().multiply(new BigDecimal(orderInfo.getGoodsCount())));
            }
            catch (Exception e)
            {
                //System.out.println(orderInfo.getOrId());
            }
        }

        return new DataGridView(page.getTotal(),orderVoList,amount);
    }


    @RequestMapping("providedGoods")
    public ResultObj providedGoods(Integer orderId) {

        OrderGoods orderGoods = orderGoodsService.getById(orderId);
        if (orderGoods != null) {
            orderGoods.setState(1);
            orderGoodsService.updateById(orderGoods);
            return ResultObj.UPDATE_SUCESS;
        } else
            return ResultObj.UPDATE_ERROR;
    }

    @RequestMapping("lackGoods")
    public ResultObj lackGoods(Integer orderId) {

        OrderGoods orderGoods = orderGoodsService.getById(orderId);
        if (orderGoods != null) {
            orderGoods.setState(2);
            orderGoodsService.updateById(orderGoods);
            return ResultObj.UPDATE_SUCESS;
        } else
            return ResultObj.UPDATE_ERROR;
    }

    @RequestMapping("setDiffWeight")
    public ResultObj setDiffWeight(Integer orderId,Integer weight) {

        OrderGoods orderGoods = orderGoodsService.getById(orderId);
        if (orderGoods != null) {
            orderGoods.setDiffWeight(weight);
            BigDecimal diffSalerPrice = (new BigDecimal(weight)).multiply(orderGoods.getSalerPrice()).divide(new BigDecimal(orderGoods.getSellWeight()));
            orderGoods.setDiffSalerMoney(diffSalerPrice);

            BigDecimal difSellPrice = (new BigDecimal(weight)).multiply(orderGoods.getSellPrice()).divide(new BigDecimal(orderGoods.getSellWeight()));
            orderGoods.setDiffMoney(difSellPrice);

            orderGoodsService.updateById(orderGoods);
            return ResultObj.UPDATE_SUCESS;
        } else
            return ResultObj.UPDATE_ERROR;
    }



}

